<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="vue-router history模式nginx配置并配置静态资源缓存">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2019-02-18-vue-router-history-mode-nginx-configuration-and-configuration-of-static-resource-cache/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="article:published_time" content="2019-02-18T10:29:49.000Z">
  <meta property="article:modified_time" content="2019-02-18T10:29:49.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="history模式">
  <meta property="article:tag" content="Nginx">
  <meta property="article:tag" content="资源缓存">
  <meta property="article:tag" content="revving">
  <meta name="twitter:card" content="summary">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2019-02-18-vue-router-history-mode-nginx-configuration-and-configuration-of-static-resource-cache/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>vue-router history模式nginx配置并配置静态资源缓存 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%83%8C%E6%99%AF"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E5%A7%8B%E9%85%8D%E7%BD%AE"><span class="nav-number">2.</span> <span class="nav-text">原始配置</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#history%E6%A8%A1%E5%BC%8F%E9%85%8D%E7%BD%AE"><span class="nav-number">3.</span> <span class="nav-text">history模式配置</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#history%E6%A8%A1%E5%BC%8F%E5%8D%87%E7%BA%A7%E7%89%88"><span class="nav-number">4.</span> <span class="nav-text">history模式升级版</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%86%8D%E6%AC%A1%E5%BA%94%E7%94%A8"><span class="nav-number">5.</span> <span class="nav-text">再次应用</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#webpack%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="nav-number">5.1.</span> <span class="nav-text">webpack的配置</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#vue-router%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="nav-number">5.2.</span> <span class="nav-text">vue-router的配置</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#nginx%E6%A0%B9%E7%9B%AE%E5%BD%95%E7%9A%84%E6%96%87%E4%BB%B6%E7%BB%93%E6%9E%84"><span class="nav-number">5.3.</span> <span class="nav-text">nginx根目录的文件结构</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#nginx%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="nav-number">5.4.</span> <span class="nav-text">nginx的配置</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AE%BF%E9%97%AE%E5%9C%B0%E5%9D%80"><span class="nav-number">5.5.</span> <span class="nav-text">访问地址</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E9%A1%B5%E9%85%8D%E7%BD%AE"><span class="nav-number">6.</span> <span class="nav-text">多页配置</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AE%BF%E9%97%AE%E5%9C%B0%E5%9D%80-1"><span class="nav-number">6.1.</span> <span class="nav-text">访问地址</span></a></li>
                    </ol>
                  </li>
                </ol>
                </li>
                <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number"></span> <span class="nav-text">参考</span></a>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2019-02-18-vue-router-history-mode-nginx-configuration-and-configuration-of-static-resource-cache/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              vue-router history模式nginx配置并配置静态资源缓存
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2019-02-18 18:29:49" itemprop="dateCreated datePublished" datetime="2019-02-18T18:29:49+08:00">2019-02-18</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span></a>
                  </span>
                </span>


                <span id="/blob/2019-02-18-vue-router-history-mode-nginx-configuration-and-configuration-of-static-resource-cache/" class="post-meta-item leancloud_visitors" data-flag-title="vue-router history模式nginx配置并配置静态资源缓存" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2>
            <ol>
              <li>vue-router配置history模式后，index.html在域名根目录，需要把页面指向index.html，加载成功后vue根据路由信息加载页面。</li>
              <li>每次更新都会更新index.html内引用资源的hash值，如何保证每次更新后不使用强制刷新就能加载正确的资源文件。</li>
            </ol>
            <h2 id="原始配置"><a href="#原始配置" class="headerlink" title="原始配置"></a>原始配置</h2>
            <p>一个基本的前端nginx会有接口转发，静态文件地址并指向默认文件。见如下代码：</p>
            <figure class="highlight bash">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">server &#123;</span><br><span class="line">    listen       80;</span><br><span class="line">    server_name  localhost;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 接口转发</span></span><br><span class="line">    location ~ ^/api &#123;</span><br><span class="line">        proxy_pass http://xxx.com:3000;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 路由和静态文件配置</span></span><br><span class="line">    location / &#123;</span><br><span class="line">        root /xxx/dist;</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="history模式配置"><a href="#history模式配置" class="headerlink" title="history模式配置"></a>history模式配置</h2>
            <p>因为history不会指向具体的html地址，需要配置无法读取静态文件的地址指向起始页。</p>
            <figure class="highlight bash">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">server &#123;</span><br><span class="line">    listen       80;</span><br><span class="line">    server_name  localhost;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 接口转发</span></span><br><span class="line">    location ~ ^/api &#123;</span><br><span class="line">        proxy_pass http://xxx.com:3000;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 路由和静态文件配置</span></span><br><span class="line">    location / &#123;</span><br><span class="line">        root /xxx/dist;</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line">        try_files <span class="variable">$uri</span> <span class="variable">$uri</span>/ @rewrites;    </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 路由index.html配置</span></span><br><span class="line">    location @rewrites &#123;</span><br><span class="line">         rewrite ^(.+)$ /index.html <span class="built_in">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="history模式升级版"><a href="#history模式升级版" class="headerlink" title="history模式升级版"></a>history模式升级版</h2>
            <p>在实际生产活动中，每一次上线都希望发布的的内容不需要用户强制刷新即可呈现在用户的眼前。</p>
            <p>因此根据history模式的实际情况，首先对指定了具体文件格式的静态文件设定30天的有效期；<br>其次路由访问的index.html设置为不缓存。</p>
            <p><strong>注意：</strong></p>
            <p>这个配置针对具有hash值的静态文件，先设置强制缓存，再设置协商缓存；如果存在没有hash值的静态文件，建议不设置强制缓存，仅通过协商缓存判断是否需要使用缓存。</p>
            <p>因此当前配置仅指定index.html无强制缓存，其他具有hash的静态文件有强制缓存。</p>
            <figure class="highlight bash">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">server &#123;</span><br><span class="line">    listen       80;</span><br><span class="line">    server_name  localhost;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 静态文件设定30天的有效期</span></span><br><span class="line">    location ~ \.(html|css|js|jpg|png|gif|swf|woff|woff2|eot|svg|ttf|otf|mp3|m4a|aac|txt)$ &#123;</span><br><span class="line">        root   /xxx/dist;</span><br><span class="line">        expires 30d;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 接口转发</span></span><br><span class="line">    location ~ ^/api &#123;</span><br><span class="line">        proxy_pass http://xxx.com:3000;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 路由配置页面无缓存</span></span><br><span class="line">    location / &#123;</span><br><span class="line">        root /xxx/dist;</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line">        expires -1;</span><br><span class="line">        add_header Cache-Control no-cache;</span><br><span class="line">        try_files <span class="variable">$uri</span> <span class="variable">$uri</span>/ @rewrites;    </span><br><span class="line">    &#125;</span><br><span class="line">    location @rewrites &#123;</span><br><span class="line">         rewrite ^(.+)$ /index.html <span class="built_in">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="再次应用"><a href="#再次应用" class="headerlink" title="再次应用"></a>再次应用</h2>
            <p>上面使用的配置皆是在一个域名下面只有一套静态页面，此次解决同一个域名多套静态页面，共用一个服务端接口。</p>
            <h3 id="webpack的配置"><a href="#webpack的配置" class="headerlink" title="webpack的配置"></a>webpack的配置</h3>
            <p>输出编译后文件到项目根目录下的output/app_static目录下。当然因为多个项目，每个项目的名称肯定不同。</p>
            <p>在此处<code>webpack</code>的配置中<code>moduleName</code>作为当前项目的名称.</p>
            <p>编译后引用的资源文件路径前缀是<code>/app_static/xxx/xxx.xx</code></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> projectRoot = process.cwd();</span><br><span class="line"><span class="keyword">const</span> webpack = <span class="built_in">require</span>(<span class="string">&#x27;webpack&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> moduleName = <span class="string">&#x27;app&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> staticName = <span class="string">`<span class="subst">$&#123;moduleName&#125;</span>_static`</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  entry: <span class="string">&quot;./public/main/app.js&quot;</span>,</span><br><span class="line"></span><br><span class="line">  output: &#123;</span><br><span class="line">    libraryTarget: <span class="string">&#x27;var&#x27;</span>,</span><br><span class="line">    path: path.resolve(projectRoot, <span class="string">&#x27;./output/&#x27;</span> + staticName + <span class="string">&#x27;/&#x27;</span>),</span><br><span class="line">    publicPath: <span class="string">&#x27;/&#x27;</span> + staticName + <span class="string">&#x27;/&#x27;</span>,</span><br><span class="line">    filename: <span class="string">&#x27;[name]_[hash:8].js&#x27;</span>,</span><br><span class="line">    chunkFilename: <span class="string">&#x27;[name]_[hash:8].js&#x27;</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  plugins: [</span><br><span class="line">    <span class="comment">// ......</span></span><br><span class="line">    <span class="keyword">new</span> webpack.DefinePlugin(&#123;</span><br><span class="line">      ENV: <span class="built_in">JSON</span>.stringify(<span class="string">&#x27;online&#x27;</span>),</span><br><span class="line">      MODULE_NAME: <span class="built_in">JSON</span>.stringify(moduleName)</span><br><span class="line">    &#125;),</span><br><span class="line">    <span class="comment">// ......</span></span><br><span class="line">  ],</span><br><span class="line">  <span class="comment">// ......</span></span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <h3 id="vue-router的配置"><a href="#vue-router的配置" class="headerlink" title="vue-router的配置"></a>vue-router的配置</h3>
            <p>路由前缀为<code>/app/xxx/xxx</code></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  mode: <span class="string">&#x27;history&#x27;</span>,</span><br><span class="line">  base: <span class="string">`/<span class="subst">$&#123;MODULE_NAME&#125;</span>/`</span>,</span><br><span class="line">  routes: [</span><br><span class="line">    &#123;</span><br><span class="line">      path: <span class="string">&#x27;&#x27;</span>,</span><br><span class="line">      name: <span class="string">`/<span class="subst">$&#123;MODULE_NAME&#125;</span>`</span>,</span><br><span class="line">      redirect: &#123; <span class="attr">name</span>: <span class="string">&#x27;home&#x27;</span> &#125;,</span><br><span class="line">      component: <span class="function"><span class="params">resolve</span> =&gt;</span> <span class="built_in">require</span>([<span class="string">&#x27;business&#x27;</span>], resolve),</span><br><span class="line">      children: [</span><br><span class="line">        &#123;</span><br><span class="line">          path: <span class="string">&#x27;home&#x27;</span>,</span><br><span class="line">          name: <span class="string">&#x27;home&#x27;</span>,</span><br><span class="line">          component: <span class="function"><span class="params">resolve</span> =&gt;</span> <span class="built_in">require</span>([<span class="string">&#x27;business/home&#x27;</span>], resolve)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// ......</span></span><br><span class="line">      ]</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123; </span><br><span class="line">      path: <span class="string">&#x27;*&#x27;</span>, </span><br><span class="line">      redirect: &#123; <span class="attr">name</span>: <span class="string">&#x27;home&#x27;</span> &#125;,</span><br><span class="line">      component: Vue.extend(&#123;</span><br><span class="line">        template: <span class="string">&#x27;&lt;router-view transition=&quot;fade&quot; transition-mode=&quot;out-in&quot;&gt;&lt;/router-view&gt;&#x27;</span></span><br><span class="line">      &#125;) </span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <h3 id="nginx根目录的文件结构"><a href="#nginx根目录的文件结构" class="headerlink" title="nginx根目录的文件结构"></a>nginx根目录的文件结构</h3>
            <p>nginx根目录下面存在多个项目的静态文件</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&#x2F;xxxx&#x2F;dist</span><br><span class="line">|-- app_static</span><br><span class="line">|   |-- ......</span><br><span class="line">|   &#96;-- index.html</span><br><span class="line">|</span><br><span class="line">|-- music_static</span><br><span class="line">|   |-- ......</span><br><span class="line">|   &#96;-- index.html</span><br><span class="line">&#96;-- ......</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <h3 id="nginx的配置"><a href="#nginx的配置" class="headerlink" title="nginx的配置"></a>nginx的配置</h3>
            <figure class="highlight bash">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">server &#123;</span><br><span class="line">    listen       80;</span><br><span class="line">    server_name  localhost;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 静态文件设定30天的有效期</span></span><br><span class="line">    location ~ \.(html|css|js|jpg|png|gif|swf|woff|woff2|eot|svg|ttf|otf|mp3|m4a|aac|txt)$ &#123;</span><br><span class="line">        root   /xxx/dist;</span><br><span class="line">        expires 30d;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 接口转发</span></span><br><span class="line">    location ~ ^/api &#123;</span><br><span class="line">        proxy_pass http://xxx.com:3000;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 路由配置页面无缓存</span></span><br><span class="line">    location ~ ^/(app|music)/ &#123;</span><br><span class="line">        root /xxx/dist;</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line">        expires -1;</span><br><span class="line">        add_header Cache-Control no-cache;</span><br><span class="line">        try_files <span class="variable">$uri</span> <span class="variable">$uri</span>/ @rewrites;    </span><br><span class="line">    &#125;</span><br><span class="line">    location @rewrites &#123;</span><br><span class="line">         rewrite ^/(app|music)/ /<span class="variable">$1_static</span>/index.html <span class="built_in">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>


            <h3 id="访问地址"><a href="#访问地址" class="headerlink" title="访问地址"></a>访问地址</h3>
            <p><a target="_blank" rel="noopener" href="http://localhost/app/home">http://localhost/app/home</a><br><a target="_blank" rel="noopener" href="http://localhost/music/home">http://localhost/music/home</a></p>
            <p><strong>注意</strong> history路由使用<code>app</code>前缀，资源文件路径使用<code>app_static</code>前缀，是为了更好的区分两种访问的url。</p>
            <h2 id="多页配置"><a href="#多页配置" class="headerlink" title="多页配置"></a>多页配置</h2>
            <p>上面说的仅仅是单页应用的nginx配置，对于多页的还会有所不同。</p>
            <figure class="highlight bash">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment"># 路由配置页面无缓存</span></span><br><span class="line">location ~ ^/app/module/ &#123;</span><br><span class="line">    root /xxx/dist;</span><br><span class="line">    index  index.html index.htm;</span><br><span class="line">    expires -1;</span><br><span class="line">    add_header Cache-Control no-cache;</span><br><span class="line">    try_files <span class="variable">$uri</span> <span class="variable">$uri</span>/ @rewrites;</span><br><span class="line">&#125;</span><br><span class="line">location @rewrites &#123;</span><br><span class="line">    rewrite ^/(app)\/module\/(index|about)/ /<span class="variable">$1_static</span>/module/<span class="variable">$2</span>.html <span class="built_in">break</span>;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>rewrites也可以使用最原始的方式，但是我认为这是最简洁的方式，因为需要支持module后面多个路径（定义为二级页面）。</p>
            <figure class="highlight bash">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">location @rewrites &#123;</span><br><span class="line">    rewrite ^/app/module/index /app_static/module/index.html <span class="built_in">break</span>;</span><br><span class="line">    rewrite ^/app/module/about /app_static/module/about.html <span class="built_in">break</span>;</span><br><span class="line">    <span class="comment"># 二级页面配置</span></span><br><span class="line">    rewrite ^/app/module/sale/sale_info /app_static/module/sale/sale_info.html <span class="built_in">break</span>;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h3 id="访问地址-1"><a href="#访问地址-1" class="headerlink" title="访问地址"></a>访问地址</h3>
            <p><a target="_blank" rel="noopener" href="http://localhost/app/module/index">http://localhost/app/module/index</a><br><a target="_blank" rel="noopener" href="http://localhost/app/module/about">http://localhost/app/module/about</a><br><a target="_blank" rel="noopener" href="http://localhost/app/module/sale/sale_info">http://localhost/app/module/sale/sale_info</a></p>
            <h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1>
            <p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/bigberg/p/7644192.html">https://www.cnblogs.com/bigberg/p/7644192.html</a><br><a target="_blank" rel="noopener" href="https://blog.csdn.net/fay462298322/article/details/54666636/">https://blog.csdn.net/fay462298322/article/details/54666636/</a><br><a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000002797606">https://segmentfault.com/a/1190000002797606</a></p>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/history%E6%A8%A1%E5%BC%8F/" rel="tag"># history模式</a>
              <a href="/tags/Nginx/" rel="tag"># Nginx</a>
              <a href="/tags/%E8%B5%84%E6%BA%90%E7%BC%93%E5%AD%98/" rel="tag"># 资源缓存</a>
              <a href="/tags/revving/" rel="tag"># revving</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2019-01-17-prevent-text-wrapping/" rel="prev" title="防止文字环绕">
                  <i class="fa fa-chevron-left"></i> 防止文字环绕
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2019-03-18-vue-project-add-eslint/" rel="next" title="vue 项目添加 eslint">
                  vue 项目添加 eslint <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>